package eproject.mm.com.projectsupervision.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.header.StoreHouseHeader;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.google.gson.Gson;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.activity.MessageContentActivity;
import eproject.mm.com.projectsupervision.activity.ProjectActivity;
import eproject.mm.com.projectsupervision.adapter.MessageAdapter;
import eproject.mm.com.projectsupervision.adapter.ProjectAdapter;
import eproject.mm.com.projectsupervision.util.HttpUtil;

/**
 * A simple {@link Fragment} subclass.
 */
public class MessageFragment extends Fragment {
    ListView msgList = null;
    MessageAdapter msgAdapter = null;

    LoadingDialog loadingDialog = null;
    private PtrClassicFrameLayout ptrFrameLayout;

    int page = 1;
    List listData = new ArrayList();

    public MessageFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_message, container, false);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null
                && savedInstanceState.getBoolean("isConflict", false))
            return;

        msgList = (ListView) getView().findViewById(R.id.msgList);
        msgList.setDivider(null);

        ptrFrameLayout = (PtrClassicFrameLayout)getView().findViewById(R.id.ptrFL_message);

        //下拉刷新支持时间
        ptrFrameLayout.setLastUpdateTimeRelateObject(this);
        //下拉刷新一些设置 详情参考文档
        ptrFrameLayout.setResistance(1.7f);
        ptrFrameLayout.setRatioOfHeaderHeightToRefresh(1.2f);
        ptrFrameLayout.setDurationToClose(200);
        ptrFrameLayout.setDurationToCloseHeader(1000);
        // default is false
        ptrFrameLayout.setPullToRefresh(false);
        // default is true
        ptrFrameLayout.setKeepHeaderWhenRefresh(true);

        initEvent();
        //loadList();
    }

    private void initEvent(){
        msgList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View v, int posation,
                                    long l) {
                Map itemMap = msgAdapter.getItem(posation);
                String id = (String)itemMap.get("id");

                Intent intent = new Intent(getActivity(), MessageContentActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("id", id);
                intent.putExtras(bundle);
                startActivityForResult(intent,0);
            }
        });

        ptrFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            //在这里进行数据加载
            public void onRefreshBegin(PtrFrameLayout frame) {
                page = 1;
                loadList();
            }
        });
        ptrFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                page++;
                loadList();
            }
        });

        ptrFrameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrFrameLayout.autoRefresh(true);
            }
        }, 150);
    }

    private void loadList() {
        loadingDialog = new LoadingDialog(getContext());
        loadingDialog.setLoadingText("加载中..."+"").show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String projectStr = HttpUtil.get("/getPushMsgList?page="+page);

                    handler.sendMessage(handler.obtainMessage(1, projectStr));
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_LONG);
                    loadingDialog.close();
                }
            }
        }).start();
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String str = (String)msg.obj;
                    Gson gson=new Gson();
                    Map resultMap = gson.fromJson(str, Map.class);
                    if (resultMap != null && resultMap.containsKey("success") && (boolean) resultMap.get("success")) {
                        List rows = (List) resultMap.get("rows");
                        int pages = Integer.parseInt((String)resultMap.get("pages"));

                        loadingDialog.close();
                        if(page==1) {
                            listData.clear();
                            listData.addAll(rows);
                            if(msgAdapter == null) {
                                msgAdapter = new MessageAdapter(getContext(), listData);
                                msgList.setAdapter(msgAdapter);
                            }
                            msgAdapter.notifyDataSetChanged();

                            ptrFrameLayout.refreshComplete();

                            if(page < pages){
                                if (!ptrFrameLayout.isLoadMoreEnable()) {
                                    ptrFrameLayout.setLoadMoreEnable(true);
                                }
                            }
                        }else{
//                            msgAdapter.addItems(rows);
//                            msgList.setAdapter(msgAdapter);
                            listData.addAll(rows);
                            msgAdapter.notifyDataSetChanged();

                            ptrFrameLayout.loadMoreComplete(true);
                            if(page == pages){
                                if (ptrFrameLayout.isLoadMoreEnable()) {
                                    ptrFrameLayout.setLoadMoreEnable(false);
                                }
                            }
                        }
                    }else{
                        loadingDialog.close();
                        ptrFrameLayout.refreshComplete();
                        if (ptrFrameLayout.isLoadMoreEnable()) {
                            ptrFrameLayout.setLoadMoreEnable(false);
                        }
                    }
                    break;
                case 2:
                    ptrFrameLayout.refreshComplete();
                    if (ptrFrameLayout.isLoadMoreEnable()) {
                        ptrFrameLayout.setLoadMoreEnable(false);
                    }
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };
}
